<template>
  <view class="container">
    <!-- 顶部标题栏 -->
    <view class="header">
      <view class="header-content">
        <text class="header-title">首页</text>
      </view>
      <view class="location-section" @click="navigateToCitySelect">
        <image class="location-icon" src="../../static/icon-Myaddress.png" mode="aspectFit" style="width: 16px; height: 16px;"></image>
        <text class="location-text">{{ currentAddress || '焦作市山阳区人民路32号' }}</text>
        <image class="refresh-icon" src="../../static/icon-refresh.png" mode="aspectFit" @click.stop="getLocation(true)" style="width: 16px; height: 16px; margin-left: 5px;"></image>
      </view>
    </view>

    <!-- 搜索栏（已注释，图片中未显示）
    <view class="search-section">
      <view class="search-input-container">
        <image class="search-icon" src="../../static/icon-Mapaddress.png" mode="aspectFit"></image>
        <input type="text" v-model="searchKeyword" placeholder="搜索加油站名称、地址" @confirm="handleSearch" />
      </view>
      <view class="filter-section">
        <view class="filter-item" @click="toggleFilter('price')">
          <text class="filter-text">价格</text>
          <image class="filter-icon" src="../../static/icon-right.png" mode="aspectFit"></image>
        </view>
        <view class="filter-item" @click="toggleFilter('distance')">
          <text class="filter-text">距离</text>
          <image class="filter-icon" src="../../static/icon-right.png" mode="aspectFit"></image>
        </view>
        <view class="filter-item" @click="toggleFilter('brand')">
          <text class="filter-text">品牌</text>
          <image class="filter-icon" src="../../static/icon-right.png" mode="aspectFit"></image>
        </view>
      </view>
    </view>
    -->

    <!-- 服务推荐区域 -->
    <view class="service-section">
      <view class="service-list">
        <view class="service-item" @click="navigateToService('repair')">
          <view class="service-card">
            <image class="service-img" src="../../static/icon-car.png" mode="aspectFit"></image>
          </view>
          <text class="service-text">车辆维修</text>
        </view>
        <view class="service-item" @click="navigateToService('maintain')">
          <view class="service-card">
            <image class="service-img" src="../../static/icon-car.png" mode="aspectFit"></image>
          </view>
          <text class="service-text">汽车保养</text>
        </view>
        <view class="service-item" @click="navigateToService('wash')">
          <view class="service-card">
            <image class="service-img" src="../../static/icon-car.png" mode="aspectFit"></image>
          </view>
          <text class="service-text">专业洗车</text>
        </view>
        <view class="service-item" @click="navigateToService('gas')">
          <view class="service-card">
            <image class="service-img" src="../../static/icon-car.png" mode="aspectFit"></image>
          </view>
          <text class="service-text">就近加油</text>
        </view>
      </view>
    </view>

    <!-- 附近加油站区域 -->
    <view class="nearby-section">
      <view class="section-header">
        <text class="section-title">附近加油站</text>
        <view class="view-more" @click="viewMapMode">
          <text class="view-more-text">全部</text>
          <image class="view-more-icon" src="../../static/icon-right.png" mode="aspectFit"></image>
        </view>
      </view>
      
      <!-- 地图视图 -->
        <view class="map-container">
          <!-- 使用真实地图组件 -->
          <map 
            id="map" 
            :latitude="latitude" 
            :longitude="longitude" 
            :markers="markers" 
            :show-location="true" 
            style="width: 100%; height: 300px;" 
            @markertap="handleMarkerTap"
          ></map>
        </view>

      <!-- 加油站列表（已注释，根据图片只显示地图视图） -->
      <!-- 
      <view class="station-list">
        <view 
          v-for="(station, index) in sortedStations" 
          :key="station.id"
          class="station-item"
          @click="navigateToDetail(station)"
        >
          <view class="station-main">
            <image src="../../static/icon-car.png" class="station-image"></image>
            <view class="station-info">
              <view class="station-name-row">
                <text class="station-name">{{ station.name }}</text>
                <text class="station-brand">{{ station.brand || '民营' }}</text>
              </view>
              <view class="station-meta">
                <text class="station-distance">{{ station.distance }}</text>
                <text class="station-price">{{ station.detail.price || '价格待定' }}</text>
                <text class="station-rating">⭐{{ station.detail.rating || '4.5' }}</text>
              </view>
              <view class="station-address">{{ station.address }}</view>
            </view>
          </view>
          <view class="station-actions">
            <view class="action-item navigate" @click.stop="handleNavigate(station)">
              <image class="action-icon" src="../../static/icon-address.png" mode="aspectFit"></image>
              <text class="action-text">导航</text>
            </view>
          </view>
        </view>
      </view>

      <! 加载提示 -->
      <view class="loading-section" v-if="loading">
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 空状态 -->
      <view class="empty-section" v-if="!loading && sortedStations.length === 0">
        <image class="empty-icon" src="../../static/icon-car.png" mode="aspectFit"></image>
        <text class="empty-text">暂无加油站数据</text>
      </view>
      -->
    </view>

    <!-- 优惠团购区域 -->
    <view class="discount-section">
      <view class="section-header">
        <text class="section-title">优惠团购</text>
        <view class="view-more" @click="navigateToGroupBuyList">
          <text class="view-more-text">更多</text>
          <image class="view-more-icon" src="../../static/icon-right.png" mode="aspectFit"></image>
        </view>
      </view>
      <view class="discount-list">
        <view class="discount-item" @click="navigateToGroupBuyDetail('1')">
          <image class="discount-image" src="https://img95.699pic.com/xsj/18/vt/8o.jpg!/fh/300" mode="aspectFill"></image>
          <text class="discount-title">北京四日追花拍摄秘密-故宫</text>
        </view>
        <view class="discount-item" @click="navigateToGroupBuyDetail('2')">
          <image class="discount-image" src="https://img95.699pic.com/xsj/18/vt/8o.jpg!/fh/300" mode="aspectFill"></image>
          <text class="discount-title">北京四日追花拍摄秘密-故宫</text>
        </view>
      </view>
    </view>

    <!-- 搜索结果面板 -->
    <view class="search-result-panel" v-if="showSearchResult">
      <view class="search-result-header">
        <text class="search-result-title">搜索结果 ({{ searchResults.length }})</text>
        <view class="search-result-close" @click="closeSearchResult">
          <text>×</text>
        </view>
      </view>
      <view class="search-result-content">
        <view class="search-loading" v-if="searchLoading">
          <text>正在搜索中...</text>
        </view>
        <view v-else-if="searchResults.length === 0" class="search-result-empty">
          <text>没有找到相关加油站</text>
        </view>
        <view class="search-result-list" v-else>
          <view 
            class="search-result-item" 
            v-for="station in searchResults" 
            :key="station.id"
            @click="handleSearchResultClick(station)"
          >
            <view class="station-info-content">
              <view class="station-name-distance">
                <text class="station-name-text">{{ station.name }}</text>
                <text class="station-distance-text">{{ station.distance }}</text>
              </view>
              <text class="station-address-text">{{ station.address }}</text>
              <view class="station-extra-info">
                <text class="station-price-info">{{ station.detail.price || '价格待定' }}</text>
                <text class="station-brand-info">{{ station.brand || '民营' }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 筛选面板（已注释，图片中未显示） -->
      <!-- <view class="filter-panel" v-if="showFilterPanel">
        <view class="filter-panel-header">
          <text class="filter-panel-title">{{ getFilterTitle() }}</text>
          <view class="filter-panel-close" @click="closeFilter">
            <text>×</text>
          </view>
        </view>
        <view class="filter-panel-content">
          <view class="filter-option" v-for="option in getFilterOptions()" :key="option.value" @click="selectFilterOption(option)">
            <text class="filter-option-text">{{ option.label }}</text>
            <view class="filter-option-check" v-if="selectedFilterOption === option.value">
              <text>✓</text>
            </view>
          </view>
        </view>
      </view> -->
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
// 从全局获取QQMapWX类（已在main.ts中导入并挂载）
const getQQMapWXClass = () => {
  try {
    // 首先尝试获取全局注入的QQMapWX
    if (typeof globalThis.QQMapWX !== 'undefined') {
      console.log('✓ 成功获取全局QQMapWX类');
      return globalThis.QQMapWX;
    }
    
    // 尝试从window获取（在浏览器环境）
    if (typeof window !== 'undefined' && window.QQMapWX) {
      console.log('✓ 从window获取QQMapWX类');
      return window.QQMapWX;
    }
    
    // 尝试通过动态导入获取
    try {
      console.log('尝试动态导入QQMapWX');
      const QQMapWX = require('../../static/js/qqmap-wx-jssdk.min.js');
      console.log('✓ 动态导入QQMapWX成功');
      return QQMapWX;
    } catch (importError) {
      console.warn('动态导入失败:', importError.message || String(importError));
    }
    
    console.warn('无法获取QQMapWX类，将使用WebService API兼容模式');
    return null;
  } catch (error) {
    console.error('获取QQMapWX类时发生错误:', error);
    return null;
  }
};

// 初始化QQMapWX实例
const initQQMapSDK = (key) => {
  try {
    console.log('初始化地图SDK，使用本地qqmap-wx-jssdk.min.js');
    
    // 获取QQMapWX类
    const QQMapWXClass = getQQMapWXClass();
    
    if (QQMapWXClass) {
      // 如果成功获取到类，创建实例
      const sdkInstance = new QQMapWXClass({ key });
      console.log('地图SDK实例创建成功');
      return sdkInstance;
    }
    
    // 降级方案：使用WebService API兼容模式
    console.log('启用WebService API兼容模式');
    const WebServiceAPI = class {
      constructor(options) {
        this.key = options.key || 'IP6BZ-VFXHT-SJIXQ-LOD5I-FUOXF-J7BPV';
        console.log('初始化WebService API兼容模式，密钥:', this.key);
      }
      
      reverseGeocoder(options) {
        const { location, success, fail } = options;
        if (!location) {
          fail && fail({ status: -1, message: '位置参数不能为空' });
          return;
        }
        
        try {
          uni.request({
            url: 'https://apis.map.qq.com/ws/geocoder/v1/',
            method: 'GET',
            data: { location, key: this.key },
            success: (res) => res.statusCode === 200 && res.data ? success(res.data) : fail(res.data || { status: res.statusCode }),
            fail: (error) => fail({ status: -1, message: '请求失败', error })
          });
        } catch (e) {
          fail && fail({ status: -1, message: '处理失败', error: e });
        }
      }
      
      search(options) {
        const { keyword, location, radius, success, fail } = options;
        if (!keyword || !location) {
          fail && fail({ status: -1, message: '关键词或位置参数不能为空' });
          return;
        }
        
        try {
          uni.request({
            url: 'https://apis.map.qq.com/ws/place/v1/search',
            method: 'GET',
            data: {
              keyword,
              location,
              radius: radius || 5000,
              key: this.key,
              page_size: 20
            },
            success: (res) => res.statusCode === 200 && res.data ? success(res.data) : fail(res.data || { status: res.statusCode }),
            fail: (error) => fail({ status: -1, message: '请求失败', error })
          });
        } catch (e) {
          fail && fail({ status: -1, message: '处理失败', error: e });
        }
      }
    };
    
    return new WebServiceAPI({ key });
  } catch (error) {
    console.error('地图SDK初始化失败:', error);
    // 返回基本的mock对象确保应用不会崩溃
    return {
      reverseGeocoder: (options) => options.fail && options.fail({ status: -1, message: '地图服务不可用' }),
      search: (options) => options.fail && options.fail({ status: -1, message: '地图服务不可用' })
    };
  }
};

// 响应式数据
const searchKeyword = ref('');
const locationDesc = ref('获取位置中...');
const loading = ref(true);
const stations = ref([]);
const searchResults = ref([]);
const searchLoading = ref(false);
const showSearchResult = ref(false);
const filterActive = ref('');
const showFilterPanel = ref(false);
const selectedFilterOption = ref('');
const currentAddress = ref('焦作市山阳区人民路32号'); // 当前地址

// 获取城市的地址和经纬度（使用腾讯地图搜索API）
const getCityRandomAddress = (city) => {
  return new Promise((resolve, reject) => {
    try {
      // 首先使用腾讯地图搜索API获取城市中心的经纬度
      uni.request({
        url: `https://apis.map.qq.com/ws/place/v1/suggestion?keyword=${encodeURIComponent(city)}&key=${QQMAP_KEY}`,
        method: 'GET',
        success: (res) => {
          if (res.data && res.data.status === 0 && res.data.data && res.data.data.length > 0 && res.data.data[0].location) {
            const cityData = res.data.data[0];
            const cityLocation = cityData.location;
            
            // 再使用腾讯地图的地点搜索API获取该城市的热门地点
            uni.request({
              url: `https://apis.map.qq.com/ws/place/v1/search?boundary=nearby(${cityLocation.lat},${cityLocation.lng},5000)&keyword=${encodeURIComponent('热门地点')}&key=${QQMAP_KEY}`,
              method: 'GET',
              success: (placeRes) => {
                let address = `${city}市中心`;
                
                if (placeRes.data && placeRes.data.status === 0 && placeRes.data.data && placeRes.data.data.length > 0) {
                  // 随机选择一个热门地点
                  const randomPlace = placeRes.data.data[Math.floor(Math.random() * placeRes.data.data.length)];
                  address = randomPlace.address || randomPlace.title;
                } else {
                  // 如果没有获取到热门地点，使用城市名+区域作为地址
                  if (cityData.district) {
                    address = `${city}市${cityData.district}`;
                  }
                }
                
                // 生成随机偏移量（-0.01 到 0.01 度，大约 1 公里范围）
                const latOffset = (Math.random() - 0.5) * 0.02;
                const lngOffset = (Math.random() - 0.5) * 0.02;
                
                // 返回城市数据
                resolve({
                  city: city,
                  address: address,
                  latitude: cityLocation.lat + latOffset,
                  longitude: cityLocation.lng + lngOffset
                });
              },
              fail: (placeError) => {
                console.error('获取城市热门地点失败:', placeError);
                // 如果获取热门地点失败，直接使用城市中心坐标
                resolve({
                  city: city,
                  address: `${city}市中心`,
                  latitude: cityLocation.lat,
                  longitude: cityLocation.lng
                });
              }
            });
          } else {
            // 详细记录API失败原因
            console.warn(`未找到城市信息: ${city}`);
            // 不使用默认坐标，返回空位置信息表示定位失败
            reject({
              code: res.data?.status || 'NOT_FOUND',
              message: `获取${city}位置信息失败，请稍后再试`,
              city: city
            });
          }
        },
        fail: (error) => {
          console.error('获取城市坐标失败:', error);
          // 不使用默认坐标，返回空位置信息表示定位失败
          reject({
            code: 'NETWORK_ERROR',
            message: '网络请求失败，请检查网络连接后重试',
            city: city
          });
        }
      });
    } catch (error) {
      console.error('获取城市地址时发生异常:', error);
      // 不使用默认坐标，返回空位置信息表示定位失败
      reject({
        code: 'EXCEPTION',
        message: '获取城市信息时发生异常，请稍后重试',
        city: city
      });
    }
  });
};

// 定位数据
const latitude = ref(35.2655); // 默认纬度（郑州高新区）
const longitude = ref(113.6229); // 默认经度（郑州高新区）
const markers = ref([]); // 地图标记
let mapContext = null; // 地图上下文

// 生成模拟加油站数据（包含经纬度）
const generateMockStationsWithLocation = (centerLat, centerLng) => {
  // 模拟加油站数据，添加经纬度信息
  const baseStations = [
    { id: 1, name: '汽车兜兜', address: '山阳区人民路32号' },
    { id: 2, name: '车网联盟', address: '解放区民主路128号' },
    { id: 3, name: '微旅充汽', address: '山阳区塔南路45号' },
    { id: 4, name: '小烷充电', address: '马村区建设东路66号' },
    { id: 5, name: '快快广', address: '山阳区太行路18号' },
    { id: 6, name: '测测加油站', address: '山阳区丰收路22号' }
  ];
  
  // 为每个加油站生成随机的经纬度偏移
  return baseStations.map(station => {
    // 生成0.01到0.03度之间的随机偏移
    const latOffset = (Math.random() - 0.5) * 0.06;
    const lngOffset = (Math.random() - 0.5) * 0.06;
    
    return {
      ...station,
      latitude: centerLat + latOffset,
      longitude: centerLng + lngOffset,
      distance: `${(Math.random() * 5 + 0.5).toFixed(1)}km`
    };
  });
};

// 更新地图标记
const updateMapMarkers = (lat, lng, stations) => {
  if (!lat || !lng) return;
  
  // 当前位置标记
  const currentMarker = {
    id: 0,
    latitude: lat,
    longitude: lng,
    width: 36,
    height: 36,
    iconPath: '../../static/icon-Myaddress.png',
    title: '我的位置',
    zIndex: 999
  };
  
  // 生成加油站标记
  const stationMarkers = stations.map((station, index) => ({
    id: index + 1,
    latitude: station.latitude,
    longitude: station.longitude,
    width: 32,
    height: 32,
    iconPath: '../../static/icon-Mapaddress.png',
    title: station.name,
    callout: {
      content: station.name,
      display: 'BYCLICK',
      padding: 10,
      borderRadius: 5,
      bgColor: '#fff',
      color: '#333'
    },
    zIndex: 100 + index,
    stationData: station
  }));
  
  // 合并所有标记
  markers.value = [currentMarker, ...stationMarkers];
  
  // 调整地图视角
  setTimeout(() => {
    if (mapContext && markers.value.length > 0) {
      const points = markers.value.map(m => ({ latitude: m.latitude, longitude: m.longitude }));
      mapContext.includePoints({
        points: points,
        padding: [100, 100, 100, 100]
      });
    }
  }, 500);
};

// 跳转到团购列表页面
const navigateToGroupBuyList = () => {
  uni.navigateTo({
    url: '/pages/groupBuy/groupBuyList'
  });
};

// 跳转到团购详情页面
const navigateToGroupBuyDetail = (id) => {
  uni.navigateTo({
    url: `/pages/groupBuy/groupBuyDetail?id=${id}`
  });
};

// 跳转到城市选择页面
const navigateToCitySelect = () => {
  uni.navigateTo({
    url: '/pages/citySelect/citySelect',
    events: {
      // 接收城市选择页面返回的数据
      citySelected: (data) => {
        if (data && data.city && data.address) {
          // 更新当前地址
          currentAddress.value = data.address;
          locationDesc.value = data.address; // 同时更新locationDesc，确保UI显示正确的地址
          
          // 更新地图位置
          if (data.latitude && data.longitude) {
            latitude.value = data.latitude;
            longitude.value = data.longitude;
            
            // 重新生成站点和更新标记
            setTimeout(() => {
              const mockStations = generateMockStationsWithLocation(latitude.value, longitude.value);
              updateMapMarkers(latitude.value, longitude.value, mockStations);
              
              // 主动移动地图中心点，确保地图视图更新
              if (mapContext) {
                mapContext.moveToLocation({
                  latitude: latitude.value,
                  longitude: longitude.value,
                  success: () => {
                    console.log('地图中心点更新成功');
                  },
                  fail: (error) => {
                    console.error('地图中心点更新失败:', error);
                  }
                });
              }
            }, 100);
          }
        }
      }
    }
  });
};

// 获取地图上下文
const getMapContext = () => {
  if (!mapContext) {
    mapContext = uni.createMapContext('map');
  }
  return mapContext;
};

// 腾讯地图API密钥
// 恢复QQMAP_KEY常量定义
const QQMAP_KEY = 'IP6BZ-VFXHT-SJIXQ-LOD5I-FUOXF-J7BPV';

// 使用腾讯地图IP定位获取位置信息
// 简化的IP定位函数，避免语法错误
const getLocationByIP = async () => {
  loading.value = true;
  try {
    // 基本的IP定位实现
    const response = await uni.request({
      url: 'https://apis.map.qq.com/ws/location/v1/ip?key=IP6BZ-VFXHT-SJIXQ-LOD5I-FUOXF-J7BPV',
      method: 'GET'
    });
    
    // 简单的响应处理
    let data = response[1] || response.data || response;
    
    if (data && data.status === 0 && data.result && data.result.location) {
      // 更新位置信息
      latitude.value = data.result.location.lat;
      longitude.value = data.result.location.lng;
      
      // 使用实际地址信息而不是固定字符串
      locationDesc.value = data.result.address || '定位成功';
      currentAddress.value = data.result.address || '定位成功';
      
      // 更新地图
      await fetchNearbyGasStations(latitude.value, longitude.value);
      const mockStations = generateMockStationsWithLocation(latitude.value, longitude.value);
      updateMapMarkers(latitude.value, longitude.value, mockStations);
      
      uni.showToast({ title: 'IP定位成功', icon: 'success' });
      return true;
    }
    return false;
  } catch (error) {
    console.error('IP定位失败:', error);
    uni.showToast({ title: 'IP定位失败', icon: 'none' });
    return false;
  } finally {
    loading.value = false;
  }
};

// 获取位置信息
const getLocation = async (refresh = false) => {
  try {
    // 优先尝试使用真实定位
    await new Promise((resolve, reject) => {
      uni.getLocation({
        type: 'gcj02',
        altitude: true,
        success: async (res) => {
          console.log('获取位置成功:', res);
          latitude.value = res.latitude;
          longitude.value = res.longitude;
          
          // 使用腾讯地图逆地理编码API获取详细地址
          try {
            const geoResult = await new Promise((geoResolve, geoReject) => {
              uni.request({
                url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${res.latitude},${res.longitude}&key=${QQMAP_KEY}`,
                method: 'GET',
                success: (response) => {
                  if (response.data && response.data.status === 0 && response.data.result) {
                    geoResolve(response.data.result);
                  } else {
                    geoReject(new Error('逆地理编码失败'));
                  }
                },
                fail: geoReject
              });
            });
            
            locationDesc.value = geoResult.address || '定位成功';
            currentAddress.value = geoResult.address || '定位成功';
            
            // 不再缓存位置信息
            
          } catch (geoError) {
            console.error('获取地址信息失败:', geoError);
            locationDesc.value = '定位成功，但获取地址信息失败';
            currentAddress.value = '定位成功，但获取地址信息失败';
          }
          
          // 更新地图标记
          await fetchNearbyGasStations(res.latitude, res.longitude);
          const mockStations = generateMockStationsWithLocation(res.latitude, res.longitude);
          updateMapMarkers(res.latitude, res.longitude, mockStations);
          
          uni.showToast({ title: '定位成功', icon: 'success' });
          resolve(true);
        },
        fail: (err) => {
          console.error('获取位置失败:', err);
          // 权限被拒绝时显示明确提示
          if (err.errMsg.indexOf('auth deny') >= 0 || err.errMsg.indexOf('用户拒绝授权') >= 0) {
            uni.showModal({
              title: '位置权限未授权',
              content: '需要获取您的位置信息以便提供附近加油站服务，请在设置中开启位置权限',
              showCancel: true,
              confirmText: '去设置',
              cancelText: '暂不开启',
              success: (res) => {
                if (res.confirm) {
                  // 引导用户到设置页面
                  if (uni.openSetting) {
                    uni.openSetting({
                      success: (settingRes) => {
                        console.log('设置页面返回结果:', settingRes);
                      }
                    });
                  } else {
                    // 兼容旧版本
                    uni.showToast({
                      title: '请手动在设置中开启位置权限',
                      icon: 'none'
                    });
                  }
                }
              }
            });
          } else {
            // 其他错误情况
            uni.showToast({
              title: '获取位置失败，请检查定位服务是否开启',
              icon: 'none'
            });
          }
          reject(err);
        }
      });
    });
    return;
    
  } catch (locationError) {
    console.log('真实定位失败，尝试IP定位:', locationError);
    // 真实定位失败，尝试IP定位
    const ipLocationSuccess = await getLocationByIP();
    if (ipLocationSuccess) {
      return;
    }
    
    // 不再尝试从缓存获取位置信息
    // 不再使用默认城市，显示定位失败
    console.log('所有定位方式失败，显示定位失败提示');
    locationDesc.value = '定位失败，请检查定位服务';
    currentAddress.value = '定位失败，请检查定位服务';
    
    // 清除地图标记
    mapContext?.clearMarkers();
    
    // 显示定位失败提示
    uni.showToast({
      title: '定位失败，请手动选择城市',
      icon: 'none',
      duration: 2000
    });
  } finally {
    loading.value = false;
  }
};


// 组件挂载后初始化地图上下文
onMounted(() => {
  getMapContext();
  getLocation();
  
  // 生成模拟加油站数据并更新地图标记
  setTimeout(() => {
    const mockStations = generateMockStationsWithLocation(latitude.value, longitude.value);
    updateMapMarkers(latitude.value, longitude.value, mockStations);
  }, 100);
  
  // 添加全局事件监听，确保能接收到城市选择页面返回的数据
  uni.$on('citySelected', (data) => {
    if (data && data.city && data.address) {
      // 更新当前地址
      currentAddress.value = data.address;
      locationDesc.value = data.address; // 同时更新locationDesc，确保UI显示正确的地址
      
      // 更新地图位置
      if (data.latitude && data.longitude) {
        latitude.value = data.latitude;
        longitude.value = data.longitude;
        
        // 重新生成站点和更新标记
        setTimeout(() => {
          const mockStations = generateMockStationsWithLocation(latitude.value, longitude.value);
          updateMapMarkers(latitude.value, longitude.value, mockStations);
          
          // 主动移动地图中心点，确保地图视图更新
          if (mapContext) {
            mapContext.moveToLocation({
              latitude: latitude.value,
              longitude: longitude.value,
              success: () => {
                console.log('地图中心点更新成功');
              },
              fail: (error) => {
                console.error('地图中心点更新失败:', error);
              }
            });
          }
        }, 100);
      }
    }
  });
});

// 页面卸载时移除事件监听
onUnmounted(() => {
  uni.$off('citySelected');
});

// 权限被拒绝的处理函数
const handleLocationError = (err) => {
  console.error('定位失败:', err.message || err.errMsg || String(err));
  generateMockStations();
  
  // 权限被拒绝的处理
  if (err.errMsg && (err.errMsg.includes('auth deny') || err.errMsg.includes('auth denied'))) {
    uni.showModal({
      title: '位置权限',
      content: '需要您的位置权限才能显示附近加油站，请前往设置开启',
      confirmText: '去设置',
      cancelText: '取消',
      success: (modalRes) => {
        if (modalRes.confirm && uni.openSetting) {
          uni.openSetting();
        }
      }
    });
  }
  
  // 显示错误提示
  uni.showToast({
    title: '获取位置失败',
    icon: 'none'
  });
  
  loading.value = false;
};

// 刷新定位功能
const refreshLocation = () => {
  console.log('刷新定位...');
  // 清除缓存的位置信息
  uni.removeStorageSync('userLocation');
  // 重置状态
  loading.value = true;
  locationDesc.value = '获取位置中...';
  // 获取新位置
  getLocation();
};

// 获取附近加油站数据
const fetchNearbyGasStations = async (lat, lng) => {
  console.log('开始获取附近加油站数据...');
  try {
    // 使用新的初始化方法
    const mapSDK = initQQMapSDK(QQMAP_KEY);

    // 使用Promise包装异步调用
    const searchPromise = new Promise((resolve, reject) => {
      mapSDK.search({
        keyword: '加油站',
        location: `${lat},${lng}`,
        radius: 20000,
        success: (res) => resolve(res),
        fail: (error) => reject(error)
      });
    });

    const searchResult = await searchPromise;
    console.log('获取加油站数据成功:', searchResult);

    if (searchResult.status === 0 && searchResult.data && searchResult.data.length > 0) {
      // 处理返回结果
      const processedResults = searchResult.data.map((item, index) => {
        // 确保location存在
        if (!item.location || !item.location.lat || !item.location.lng) {
          console.warn('位置数据不完整，跳过此加油站');
          return null;
        }
        
        // 计算距离
        const distance = item._distance 
          ? `${(item._distance / 1000).toFixed(1)}km` 
          : calculateDistance(lat, lng, item.location.lat, item.location.lng);
        
        // 提取品牌信息
        const brand = extractBrandFromName(item.title || '');
        
        // 根据品牌调整价格范围
        let priceBase = 7.5;
        switch(brand) {
          case '中石化':
          case '中石油':
            priceBase = 7.8;
            break;
          case '壳牌':
          case 'BP':
          case '道达尔':
            priceBase = 7.9;
            break;
          default:
            priceBase = 7.5;
        }
        
        // 补充必要信息
        const supplementInfo = {
          price: `${(Math.random() * 0.5 + priceBase).toFixed(2)}元/升`,
          rating: `${(Math.random() * 0.8 + 4.2).toFixed(1)}`,
          openTime: Math.random() > 0.1 ? '24小时营业' : '06:00-24:00',
          phone: `0391-${Math.floor(Math.random() * 9000000 + 1000000)}`,
          facilities: ['加油', '便利店', '洗车', '洗手间'].filter(() => Math.random() > 0.3)
        };
        
        return {
          id: item.id || `station_${Date.now()}_${index}`,
          latitude: item.location.lat,
          longitude: item.location.lng,
          name: item.title,
          address: item.address || '地址信息暂不可用',
          distance: distance,
          openTime: supplementInfo.openTime,
          phone: supplementInfo.phone,
          brand: brand,
          _distance: item._distance || parseFloat(distance) * 1000,
          facilities: supplementInfo.facilities,
          detail: {
            distance: distance.replace('km', ''),
            price: supplementInfo.price,
            rating: supplementInfo.rating,
            brand: brand,
            isOpen: true,
            facilities: supplementInfo.facilities
          }
        };
      });
      
      // 按距离排序
      processedResults.sort((a, b) => a._distance - b._distance);
      
      // 验证处理结果，确保所有必需字段都有值
      stations.value = processedResults.filter(Boolean).map(station => ({
        ...station,
        // 确保所有必要字段都有默认值
        id: station.id || `station_${Date.now()}_${Math.floor(Math.random() * 1000)}`,
        name: station.name || '未知加油站',
        address: station.address || '地址未知',
        latitude: station.latitude || lat,
        longitude: station.longitude || lng,
        distance: station.distance || '0.0km'
      }));
      
      console.log('加油站数据处理完成，共', stations.value.length, '个加油站');
    } else {
      console.warn('未找到附近加油站，返回空列表');
      stations.value = [];
      // 显示提示信息
      uni.showToast({
        title: '未找到附近加油站',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取加油站数据失败:', error.message || error.errMsg || String(error));
    stations.value = [];
    // 显示错误提示
    uni.showToast({
      title: '获取加油站数据失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 已移除模拟加油站数据生成函数，现在使用真实API获取加油站数据

// 计算两点之间的距离
const calculateDistance = (lat1, lng1, lat2, lng2) => {
  const R = 6371; // 地球半径（公里）
  const dLat = (lat2 - lat1) * Math.PI / 180;
  const dLng = (lng2 - lng1) * Math.PI / 180;
  const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
            Math.sin(dLng/2) * Math.sin(dLng/2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  const distance = R * c;
  return distance < 1 ? (distance * 1000).toFixed(0) + 'm' : distance.toFixed(1) + 'km';
};

// 从加油站名称提取品牌信息
const extractBrandFromName = (name) => {
  const brandKeywords = {
    '中石化': ['中石化', '中国石化'],
    '中石油': ['中石油', '中国石油'],
    '壳牌': ['壳牌'],
    '中海油': ['中海油', '中国海油'],
    '道达尔': ['道达尔'],
    'BP': ['BP'],
    '埃索': ['埃索'],
    '延长壳牌': ['延长壳牌']
  };
  
  for (const [brand, keywords] of Object.entries(brandKeywords)) {
    for (const keyword of keywords) {
      if (name.includes(keyword)) {
        return brand;
      }
    }
  }
  
  return '民营';
};

// 计算排序后的加油站列表
const sortedStations = computed(() => {
  let result = [...stations.value];
  
  if (selectedFilterOption.value) {
    switch (filterActive.value) {
      case 'price':
        if (selectedFilterOption.value === 'asc') {
          result.sort((a, b) => {
            const priceA = parseFloat(a.detail.price);
            const priceB = parseFloat(b.detail.price);
            return priceA - priceB;
          });
        } else if (selectedFilterOption.value === 'desc') {
          result.sort((a, b) => {
            const priceA = parseFloat(a.detail.price);
            const priceB = parseFloat(b.detail.price);
            return priceB - priceA;
          });
        }
        break;
      case 'distance':
        result.sort((a, b) => a._distance - b._distance);
        break;
      case 'brand':
        const brandOrder = {'中石油': 1, '中石化': 2, '壳牌': 3, '道达尔': 4, '民营': 5};
        result.sort((a, b) => (brandOrder[a.brand] || 999) - (brandOrder[b.brand] || 999));
        break;
    }
  }
  
  return result;
});

// 处理搜索
const handleSearch = () => {
  if (!searchKeyword.value.trim()) {
    uni.showToast({ title: '请输入搜索关键词', icon: 'none' });
    return;
  }
  
  searchLoading.value = true;
  showSearchResult.value = true;
  
  try {
    // 使用新的初始化方法
    const mapSDK = initQQMapSDK(QQMAP_KEY);

    mapSDK.search({
      keyword: searchKeyword.value,
      location: `${latitude.value},${longitude.value}`,
      radius: 20000,
      success: (res) => {
        if (res.status === 0 && res.data && res.data.length > 0) {
          // 转换搜索结果
          searchResults.value = res.data.map((item, index) => {
            const distance = item._distance 
              ? `${(item._distance / 1000).toFixed(1)}km` 
              : calculateDistance(latitude.value, longitude.value, item.location.lat, item.location.lng);
            
            const brand = extractBrandFromName(item.title || '');
            const priceBase = brand === '中石化' || brand === '中石油' ? 7.8 : 7.5;
            
            return {
              id: item.id || `search_${Date.now()}_${index}`,
              name: item.title,
              address: item.address,
              latitude: item.location.lat,
              longitude: item.location.lng,
              distance: distance,
              brand: brand,
              detail: {
                price: `${(Math.random() * 0.5 + priceBase).toFixed(2)}元/升`,
                rating: `${(Math.random() * 0.8 + 4.2).toFixed(1)}`
              }
            };
          });
        } else {
          // 模拟搜索结果
          searchResults.value = stations.value.filter(station => 
            station.name.includes(searchKeyword.value) || station.address.includes(searchKeyword.value)
          );
        }
      },
      fail: (err) => {
        console.error('搜索失败:', err);
        // 降级到本地搜索
        searchResults.value = stations.value.filter(station => 
          station.name.includes(searchKeyword.value) || station.address.includes(searchKeyword.value)
        );
      },
      complete: () => {
        searchLoading.value = false;
      }
    });
  } catch (error) {
    console.error('搜索处理异常:', error);
    // 使用本地数据进行搜索
    searchResults.value = stations.value.filter(station => 
      station.name.includes(searchKeyword.value) || station.address.includes(searchKeyword.value)
    );
    searchLoading.value = false;
  }
};

// 处理搜索结果点击
const handleSearchResultClick = (station) => {
  console.log('选择搜索结果:', station.name);
  // 导航到详情页面
  navigateToDetail(station);
  // 关闭搜索结果面板
  showSearchResult.value = false;
};

// 关闭搜索结果面板
const closeSearchResult = () => {
  showSearchResult.value = false;
};

// 切换筛选面板
const toggleFilter = (type) => {
  if (filterActive.value === type && showFilterPanel.value) {
    // 关闭当前筛选面板
    closeFilter();
  } else {
    // 打开新的筛选面板
    filterActive.value = type;
    showFilterPanel.value = true;
    // 根据类型设置默认选中项
    if (type === 'distance') {
      selectedFilterOption.value = 'asc';
    }
  }
};

// 获取筛选面板标题
const getFilterTitle = () => {
  switch (filterActive.value) {
    case 'price':
      return '价格筛选';
    case 'distance':
      return '距离筛选';
    case 'brand':
      return '品牌筛选';
    default:
      return '筛选';
  }
};

// 获取筛选选项
const getFilterOptions = () => {
  switch (filterActive.value) {
    case 'price':
      return [
        { label: '价格从低到高', value: 'asc' },
        { label: '价格从高到低', value: 'desc' }
      ];
    case 'distance':
      return [
        { label: '距离最近优先', value: 'asc' },
        { label: '距离最远优先', value: 'desc' }
      ];
    case 'brand':
      return [
        { label: '中石油', value: '中石油' },
        { label: '中石化', value: '中石化' },
        { label: '壳牌', value: '壳牌' },
        { label: '道达尔', value: '道达尔' },
        { label: '民营', value: '民营' }
      ];
    default:
      return [];
  }
};

// 选择筛选选项
const selectFilterOption = (option) => {
  selectedFilterOption.value = option.value;
  // 如果是品牌筛选，直接应用筛选
  if (filterActive.value === 'brand') {
    stations.value = stations.value.filter(station => station.brand === option.value);
  }
  // 关闭筛选面板
  closeFilter();
};

// 关闭筛选面板
const closeFilter = () => {
  showFilterPanel.value = false;
};

// 处理服务点击
const handleServiceClick = (type) => {
  switch (type) {
    case 'gas':
      uni.showToast({ title: '选择了加油服务', icon: 'success' });
      break;
    case 'carwash':
      uni.showToast({ title: '选择了洗车服务', icon: 'success' });
      break;
    case 'repair':
      uni.showToast({ title: '选择了维修服务', icon: 'success' });
      break;
    case 'more':
      uni.showToast({ title: '更多服务功能开发中', icon: 'none' });
      break;
  }
};

// 导航到地图模式
const viewMapMode = () => {
  uni.navigateTo({
    url: '../detailMap/detailMap',
    success: () => {
      console.log('成功跳转到地图模式');
    },
    fail: (err) => {
      console.error('跳转失败:', err);
    }
  });
};

// 导航到详情页面
const navigateToDetail = (station) => {
  try {
    const stationData = encodeURIComponent(JSON.stringify(station));
    uni.navigateTo({
      url: `../gasStationDetail/gasStationDetail?stationData=${stationData}`,
      success: () => {
        console.log('成功跳转到详情页面');
      },
      fail: (err) => {
        console.error('跳转失败:', err);
      }
    });
  } catch (error) {
    console.error('导航处理异常:', error);
    uni.navigateTo({
      url: '../gasStationDetail/gasStationDetail',
      success: () => {
        console.log('使用备用方式跳转到详情页面');
      }
    });
  }
};

// 处理导航
const handleNavigate = (station) => {
  // 使用uni.openLocation进行导航
  uni.openLocation({
    latitude: station.latitude,
    longitude: station.longitude,
    name: station.name,
    address: station.address,
    scale: 18
  });
};

// 显示所有优惠
const showAllDiscounts = () => {
  uni.showToast({ title: '查看所有优惠', icon: 'none' });
};

// 显示优惠详情
const showDiscountDetail = (title) => {
  uni.showToast({ title: `查看优惠: ${title}`, icon: 'none' });
};

// 获取地图标记点的左侧位置
const getMarkerLeft = (index) => {
  const positions = [20, 40, 60, 80, 30, 50, 70];
  return positions[index % positions.length] + '%';
};

// 获取地图标记点的顶部位置
const getMarkerTop = (index) => {
  const positions = [30, 50, 70, 40, 60, 35, 65];
  return positions[index % positions.length] + '%';
};

// 获取简短的加油站名称，防止文字过长
const getShortStationName = (name) => {
  if (!name) return '';
  // 只显示前4个汉字或8个字符
  return name.length > 4 ? name.substring(0, 4) + '...' : name;
};


  

  


</script>

<style scoped>
.container {
  background-color: #f8f8f8;
  min-height: 100vh;
}

/* 头部样式 */
.header {
  background-color: #fff;
  padding: 15px 15px 10px 15px;
  border-bottom: 1px solid #f0f0f0;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.header-right {
  display: flex;
  gap: 15px;
}

.header-icon {
  width: 20px;
  height: 20px;
}

.location-section {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  padding: 8px 12px;
  border-radius: 15px;
  width: 100%;
}

.location-icon {
  width: 16px;
  height: 16px;
  margin-right: 5px;
}

.location-text {
  flex: 1;
  font-size: 14px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.refresh-icon {
  width: 16px;
  height: 16px;
}

/* 搜索栏样式 */
.search-section {
  padding: 10px 15px;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
}

.search-section {
  background-color: #fff;
  padding: 15px;
  margin-bottom: 10px;
}

.search-input-container {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  padding: 10px 15px;
  border-radius: 25px;
  margin-bottom: 15px;
}

.search-icon {
  width: 18px;
  height: 18px;
  margin-right: 10px;
  color: #999;
}

.search-input-container input {
  flex: 1;
  border: none;
  background: transparent;
  font-size: 14px;
  color: #333;
}

.filter-section {
  display: flex;
  justify-content: space-around;
  padding-top: 10px;
  border-top: 1px solid #f0f0f0;
}

.filter-item {
  display: flex;
  align-items: center;
  padding: 5px 15px;
  background-color: #f5f5f5;
  border-radius: 15px;
}

.filter-text {
  font-size: 14px;
  color: #666;
  margin-right: 5px;
}

.filter-icon {
  width: 12px;
  height: 12px;
  color: #999;
}

.service-section {
  background-color: #fff;
  padding: 20px 15px;
  margin-bottom: 10px;
}

.service-list {
  display: flex;
  justify-content: space-around;
}

.service-item {
  width: 25%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.service-card {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
  box-shadow: 0 2px 10px rgba(0, 128, 0, 0.3);
}

.service-card:active {
  background-color: #f0f8ff;
}

.service-img {
  width: 32px;
  height: 32px;
}

.service-text {
  font-size: 12px;
  color: #333;
  text-align: center;
}

.nearby-section {
  background-color: #fff;
  padding: 15px;
  margin-bottom: 10px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.view-more {
  display: flex;
  align-items: center;
}

.view-more-text {
  font-size: 14px;
  color: #007aff;
  margin-right: 5px;
}

.view-more-icon {
  width: 12px;
  height: 12px;
  color: #007aff;
}

/* 地图容器样式 */
.map-container {
  position: relative;
  width: 100%;
  height: 300px;
  border-radius: 10px;
  overflow: hidden;
  background-color: #f5f5f5;
}

.map-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 地图标记点样式 */
.map-marker {
  position: absolute;
  display: flex;
  flex-direction: column;
  align-items: center;
  transform: translate(-50%, -100%);
}

.marker-icon {
  width: 32px;
  height: 32px;
  z-index: 2;
}

.marker-label {
  position: absolute;
  bottom: -35px;
  padding: 4px 8px;
  background-color: rgba(0, 0, 0, 0.7);
  color: #fff;
  font-size: 11px;
  border-radius: 4px;
  white-space: nowrap;
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: inline-block;
  word-break: keep-all;
  z-index: 1;
}

.station-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.station-item {
  border: 1px solid #f0f0f0;
  border-radius: 10px;
  padding: 15px;
  transition: all 0.3s;
}

.station-item:active {
  background-color: #f5f5f5;
}

.station-main {
  display: flex;
  margin-bottom: 10px;
}

.station-image {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  margin-right: 15px;
}

.station-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.station-name-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.station-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  flex: 1;
}

.station-brand {
  font-size: 12px;
  color: #fff;
  background-color: #007aff;
  padding: 2px 8px;
  border-radius: 10px;
}

.station-meta {
  display: flex;
  gap: 15px;
  margin-bottom: 5px;
}

.station-distance {
  font-size: 14px;
  color: #ff6b6b;
}

.station-price {
  font-size: 14px;
  color: #333;
  font-weight: bold;
}

.station-rating {
  font-size: 14px;
  color: #ff9500;
}

.station-address {
  font-size: 12px;
  color: #999;
  line-height: 1.4;
}

.station-actions {
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #f0f0f0;
  padding-top: 10px;
}

.action-item {
  display: flex;
  align-items: center;
  padding: 5px 15px;
  background-color: #f5f5f5;
  border-radius: 15px;
  margin-left: 10px;
}

.action-item.navigate {
  background-color: #007aff;
}

.action-icon {
  width: 16px;
  height: 16px;
  margin-right: 5px;
}

.action-text {
  font-size: 12px;
  color: #666;
}

.action-item.navigate .action-text {
  color: #fff;
}

.loading-section {
  text-align: center;
  padding: 30px;
}

.loading-text {
  font-size: 14px;
  color: #999;
}

.empty-section {
  text-align: center;
  padding: 60px 30px;
  background-color: #fafafa;
  border-radius: 12px;
  margin: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.empty-icon {
  width: 100px;
  height: 100px;
  margin-bottom: 20px;
  opacity: 0.6;
  transition: opacity 0.3s ease;
}

.empty-section:active .empty-icon {
  opacity: 0.8;
}

.empty-text {
  font-size: 16px;
  color: #666;
  font-weight: 500;
  line-height: 1.5;
}

.search-result-panel {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  z-index: 1000;
  display: flex;
  flex-direction: column;
}

.search-result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #f8f8f8;
}

.search-result-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.search-result-close {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #999;
}

.search-result-content {
  flex: 1;
  overflow-y: auto;
}

.search-loading {
  padding: 40px 20px;
  text-align: center;
  color: #666;
}

.search-result-empty {
  padding: 40px 20px;
  text-align: center;
  color: #999;
}

.search-result-list {
  padding: 5px 0;
}

.search-result-item {
  padding: 15px;
  border-bottom: 1px solid #f5f5f5;
}

.search-result-item:active {
  background-color: #f8f8f8;
}

.station-info-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.station-name-distance {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.station-name-text {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  flex: 1;
}

.station-distance-text {
  font-size: 14px;
  color: #ff6b6b;
  background-color: #fff5f5;
  padding: 2px 8px;
  border-radius: 10px;
}

.station-address-text {
  font-size: 14px;
  color: #666;
  line-height: 1.4;
}

.station-extra-info {
  display: flex;
  gap: 20px;
  font-size: 12px;
  color: #999;
}

.station-price-info {
  font-weight: bold;
  color: #ff6b6b;
}

.station-brand-info {
  background-color: #f0f0f0;
  padding: 2px 8px;
  border-radius: 10px;
}

.filter-panel {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-radius: 20px 20px 0 0;
  box-shadow: 0 -5px 20px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.filter-panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.filter-panel-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.filter-panel-close {
  font-size: 24px;
  color: #999;
}

.filter-panel-content {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.filter-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #f5f5f5;
}

.filter-option:last-child {
  border-bottom: none;
}

.filter-option-text {
  font-size: 14px;
  color: #666;
}

.filter-option-check {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: #007aff;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 14px;
}

/* 优惠团购区域样式 */
.discount-section {
  background-color: #fff;
  padding: 15px;
  margin-bottom: 10px;
}

.discount-list {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
}

.discount-item {
  width: 48%;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.discount-item:active {
  opacity: 0.9;
}

.discount-image {
  width: 100%;
  height: 150px;
  object-fit: cover;
}

.discount-title {
  padding: 10px;
  font-size: 14px;
  color: #333;
  line-height: 1.4;
  text-align: center;
}
</style>